// import 'package:flutter/cupertino.dart' as prefix0;
import 'package:flutter/material.dart';
import './service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
// 静态router
import './routers/application.dart';



class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  // hotgoods所有的数据
  List<Map>  hotGoodsList = [];
  
  GlobalKey<RefreshFooterState> _footerkey = new GlobalKey<RefreshFooterState>();

  @override
  bool get wantKeepAlive => true;

  String homePgaeContent = '正在获取数据';

  // 初始化数据
  void initState() {
    _getHotGoods();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var formData = {'lon':'115.02','lat':'35.76'};
    return Scaffold(
        appBar: AppBar(title: Text('美好生活+')),
        // 初始化数据
        body: FutureBuilder(
          //  接受的异步方法
          future: request('homePageContent',formData:formData),
          builder: (contenx, snapshot) {
            // 判断是不是有值
            if (snapshot.hasData) {
              var data = json.decode(snapshot.data.toString());
              List<Map> swiper = (data['data']['slides'] as List).cast();
              List<Map> navigatorList =
                  (data['data']['category'] as List).cast();
              String adPicture =
                  (data['data']['advertesPicture']['PICTURE_ADDRESS']);
              String leaderImg = (data['data']['shopInfo']['leaderImage']);
              String leaderPhone = (data['data']['shopInfo']['leaderPhone']);
              List recommendList = (data['data']['recommend'] as List).cast();
              String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS'];
              String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS']; 
              String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS']; 
              List<Map> floor1 = (data['data']['floor1'] as List ).cast();
              List<Map> floor2 = (data['data']['floor2'] as List ).cast();
              List<Map> floor3 = (data['data']['floor3'] as List ).cast();

              return EasyRefresh(
                refreshFooter: ClassicsFooter(
                    key:_footerkey,
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    moreInfoColor:Colors.pink,
                    showMore: true,
                    noMoreText: '',
                    moreInfo: '加载中.....',
                    loadedText: '上拉加载',
                  ),
                child: ListView(
                  children: <Widget>[
                    SwiperItem(swiperDataList: swiper),
                    TopNavigator(navigatorList: navigatorList),
                    AddBannar(adPicture: adPicture),
                    LeaderPhone(leaderImg: leaderImg, leaderPhone: leaderPhone),
                    Recommend(recommendList: recommendList),
                    FloorTitle(pictureAddress:floor1Title),
                    FloorContent(floorGoodsList:floor1),
                    FloorTitle(pictureAddress:floor2Title),
                    FloorContent(floorGoodsList:floor2),
                    FloorTitle(pictureAddress:floor3Title),
                    FloorContent(floorGoodsList:floor3),
                    _hotGoods(),
                  ],
                ),
                loadMore:()async{
                  _getHotGoods();
                }
              );
            } else {
              return Center(child: Text('你好'));
            }
          },
         )
        );
  }
  void _getHotGoods(){
    var formData = {'page':page};
    request('homePageBelowContent',formData:formData).then((val){
      var data = json.decode(val.toString());
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
       hotGoodsList.addAll(newGoodsList);
       page++;
      });
    });
  } 

  Widget _hotTitle = Container(
    margin: EdgeInsets.only(top:10.0,bottom:10.0),
    // padding: EdgeInsets.only(bottom: 5.0),
    alignment: Alignment.center,
    child: Text('火爆专区'),
  );

  Widget _wrapList(){
    if(hotGoodsList.length!=0){
      List<Widget> listWidget = hotGoodsList.map((val){
        return  InkWell(
          onTap: (){
            Application.router.navigateTo(context, '/detail?id=${val["goodsId"]}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372.0),
            color: Colors.white,
            margin: EdgeInsets.only(bottom: 4.0),
            child: Column(
              children: <Widget>[
                Image.network(val['image'],width: ScreenUtil().setWidth(370.0)),
                Text(
                  val['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color:Colors.pink,fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${val['mallPrice']}'),
                    Text(
                      '￥${val['price']}',
                      style: TextStyle(color: Colors.black12,decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2.0,
        children:listWidget,
      );
    }else{
      return Text('');
    }
  }

  Widget _hotGoods(){
    return Container(
      child:Column(
        children: <Widget>[
          _hotTitle,
          _wrapList()
        ],
      ) ,
    );
  }
}

// 首页轮播组件
class SwiperItem extends StatelessWidget {
  final List swiperDataList;
  const SwiperItem({Key key, this.swiperDataList}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemBuilder: (BuildContext contenxt, index) {
          return InkWell(
            onTap: (){
              Application.router.navigateTo(context, '/detail?id=${swiperDataList[index]['goodsID']}');
            },
            child:Image.network("${swiperDataList[index]['image']}",
              fit: BoxFit.cover
            )
          );
        },
        itemCount: swiperDataList.length,
        // 是不是有点
        pagination: SwiperPagination(),
        // 自动播放
        autoplay: true,
      ),
    );
  }
}

// 顶部TopNavigator
class TopNavigator extends StatelessWidget {
  final List navigatorList;
  const TopNavigator({Key key, this.navigatorList}) : super(key: key);
  // 返回的是widget
  Widget _gridViewItem(BuildContext context, item) {
    return InkWell(
      onTap: () {},
      child: Column(
        children: <Widget>[
          Image.network(item['image'], width: ScreenUtil().setWidth(95)),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (navigatorList.length > 10) {
      this.navigatorList.removeRange(10, navigatorList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
          // 每行数量
          crossAxisCount: 5,
          padding: EdgeInsets.all(5.0),
          children: navigatorList.map((item) {
            return _gridViewItem(context, item);
          }).toList()),
    );
  }
}

// 广告bannar
class AddBannar extends StatelessWidget {
  final String adPicture;
  const AddBannar({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(adPicture),
    );
  }
}

// 拨打电话
class LeaderPhone extends StatelessWidget {
  final String leaderImg;
  final String leaderPhone;
  const LeaderPhone({Key key, this.leaderImg, this.leaderPhone})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: () {
          _launchURL();
        },
        child: Image.network(
          leaderImg,
          // width: ScreenUtil().setHeight(400),
        ),
      ),
    );
  }

  void _launchURL() async {
    String url = 'tel:+' + leaderPhone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'url不能经行访问 ，异常';
    }
  }
}

// 推荐模块
class Recommend extends StatelessWidget {
  final List recommendList;
  const Recommend({Key key, this.recommendList}) : super(key: key);

  Widget _titleWidget() {
    return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12)),
        ),
        child: Text('商品推荐', style: TextStyle(color: Colors.pink)));
  }

  Widget _item(context,index) {
    return InkWell(
      onTap: () {
          Application.router.navigateTo(context, '/detail?id=${recommendList[index]["goodsId"]}');
      },
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            border: Border(
          left: BorderSide(width: 0.5, color: Colors.black12),
        )),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('￥${recommendList[index]['mallPrice']}'),
            Text(
              '￥${recommendList[index]['price']}',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: Colors.black12),
            )
          ],
        ),
      ),
    );
  }

  // 横向列表
  Widget _recommedList() {
    return Container(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index) {
          return _item(context,index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: ScreenUtil().setHeight(380),
        child: Column(
          children: <Widget>[
            _titleWidget(),
            _recommedList(),
          ],
        ));
  }
}


class FloorTitle extends StatelessWidget {
  final String pictureAddress; 
  const FloorTitle({Key key,this.pictureAddress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(pictureAddress),
    );
  }
}

class FloorContent extends StatelessWidget {
  final List floorGoodsList;
  const FloorContent({Key key,this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _firstRow(context),
        _otherGoods(context)
      ],
      // child: child,
    );
  }

  Widget _otherGoods(context){
    return Row(
      children: <Widget>[
        _goodsItem(context,floorGoodsList[3]),
        _goodsItem(context,floorGoodsList[4]),
      ],
    );
  }


  Widget _firstRow(context){
    return Row(
      children: <Widget>[
        _goodsItem(context,floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context,floorGoodsList[1]),
            _goodsItem(context,floorGoodsList[2]),
          ],
        )
      ],
    );
  }

  Widget _goodsItem(context,Map goods){
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: (){
          Application.router.navigateTo(context, '/detail?id=${goods["goodsId"]}');
        },
        child: Image.network(goods['image']),
      ),
    );
  }
}


class HotGoods extends StatefulWidget {
  HotGoods({Key key}) : super(key: key);

  _HotGoodsState createState() => _HotGoodsState();
}

class _HotGoodsState extends State<HotGoods> {
  @override
  void initState() { 
    super.initState();
    request('homePageBelowContent',formData:1).then((val)=>{
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Center(),
    );
  }
}